//
//  CSViewControllerUtils.swift
//  Cycling
//
//  Created by CSS on 4/1/23.
//

import Foundation
import UIKit

extension UIViewController {
    
    func showAlert(withTitle title: String? = nil, message: String? = nil, leftTitle: String? = nil, leftStyle: UIAlertAction.Style = .default, leftBlock: (() -> Void)? = nil, rightTitle: String? = nil, rightStyle: UIAlertAction.Style = .default, rightBlock: (() -> Void)? = nil) {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        if let leftTitle = leftTitle {
            let leftAction = UIAlertAction(title: leftTitle, style: leftStyle) { _ in
                leftBlock?()
            }
            leftAction.changeTextColor(withStyle: leftStyle)
            alertController.addAction(leftAction)
        }
        
        if let rightTitle = rightTitle {
            let rightAction = UIAlertAction(title: rightTitle, style: rightStyle) { _ in
                rightBlock?()
            }
            rightAction.changeTextColor(withStyle: rightStyle)
            alertController.addAction(rightAction)
        }
        
        var presentingVC = self
        while presentingVC.presentedViewController != nil {
            presentingVC = presentingVC.presentedViewController!
        }
        presentingVC.present(alertController, animated: true)
    }
    
}

extension UIAlertAction {
    
    func changeTextColor(to color: UIColor) {
        setValue(color, forKey: "titleTextColor")
    }
    
    func changeTextColor(withStyle style: Style) {
        if style == .default {
            changeTextColor(to: .black)
        } else if style == .destructive {
            changeTextColor(to: .color(withHexString: "#0AD39F"))
        }
    }
    
}
